package example;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Exercise001 {

    public static void main(String[] args) {

        Exercise001 exercise001= new Exercise001();

        List<String> stringList = new ArrayList<>();
        stringList.add("aabbccFFFFx2x2");
        stringList.add("aaccddFFFFx2x2");
        stringList.add("aabcdFFFFx2x2");

        char[] chars = exercise001.commonChars(2, stringList);
        System.out.println(Arrays.toString(chars));


    }


    public char[] commonChars(int count, List<String> strings) {
        List<Map<Character, Integer>> totalMap = new ArrayList<Map<Character, Integer>>();
        for (String string : strings) {
            char[] charArray = string.toCharArray();
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (char c : charArray) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            map.entrySet().removeIf(entry -> entry.getValue() < count);
            totalMap.add(map);
        }

        Set<Character> resultSet = totalMap.get(0).keySet();
        for (int i = 1; i < totalMap.size(); i++) {
            Set<Character> characters1 = totalMap.get(i).keySet();
            Iterator<Character> iterator = resultSet.iterator();
            while (iterator.hasNext()) {
                Character next = iterator.next();
                if (!characters1.contains(next)) {
                    iterator.remove();
                }
            }
        }

        Character[] array = resultSet.toArray(Character[]::new);
        Arrays.sort(array);
        char[] charArray = new char[array.length];
        for (int i = 0; i < array.length; i++) {
            charArray[i] = array[i];
        }

        return charArray;
    }
}
